<template>
	<view class="form-container bg" :scroll-y="true">
        <u-sticky offset-top="10">
            <u-button @click="onScanBtn" size="normal" :icon="ruleForm.auditState !== 1 ? 'scan' : ''">
                <text v-if="ruleForm.auditState !== 1">点击扫码，当前品种: {{ ruleForm.stockRecordItemList ? ruleForm.stockRecordItemList.length : 0 }}个</text>
                <text v-else>入库品种: {{ ruleForm.stockRecordItemList ? ruleForm.stockRecordItemList.length : 0 }}个</text>
            </u-button>
        </u-sticky>
        <view v-if="activeTab === 0" class="margin-top-20">
            <view class="margin-bottom-20">
                <jkFormCard title="基本信息" :show-right-icon="ruleForm.auditState !== 1">
                    <u-icon v-if="ruleForm.auditState !== 1" slot="right" name="scan" size="24" @click="onScanBtn"></u-icon>
                    <jk-form-item label="入库单号" :show-right-icon="false">
                        <view>{{ ruleForm.code || '系统自动生成' }}</view>
                    </jk-form-item>
                    <jk-form-item label="入库仓库" :show-right-icon="ruleForm.auditState !== 1" @click="onSelectWarehouse(null)" :show-star="ruleForm.auditState !== 1" :value="ruleForm.warehouseName" @clear="onClearWarehouse">
                        <view>{{ ruleForm.warehouseName || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="入库时间" :show-right-icon="ruleForm.auditState !== 1" :show-star="ruleForm.auditState !== 1" @click="onSelectTime('belongDateTime')" :value="ruleForm.belongDateTime" @clear="ruleForm.belongDateTime = ''">
                        <view>{{ ruleForm.belongDateTime || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="备注" label-position="top" :show-border-bottom="false">
                   <textarea
                       placeholder-class="color4"
                       :class="ruleForm.auditState !== 1 ? 'textarea-style' : 'disabled-textarea-style'"
                       :disabled="ruleForm.auditState === 1"
                       :cursor-spacing="100"
                       :adjust-position="true"
                       v-model="ruleForm.remark"
                       placeholder="请输入"
                   ></textarea>
                    </jk-form-item>
                </jkFormCard>
            </view>
            <view
                v-for="(item, index) in ruleForm.stockRecordItemList"
                :key="index"
                class="margin-top-30"
            >
                <jkFormCard :title="`${index + 1}、${item.productName}`" :show-right-icon="true">
                    <u-icon v-if="ruleForm.auditState !== 1" slot="right" name="trash" size="22" color="red" @click="ruleForm.stockRecordItemList.splice(index, 1)"></u-icon>
                    <jk-form-item label="批号" :show-right-icon="false">
                        <view>{{ item.batchCode || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="成分" :show-right-icon="false">
                        <view>{{ item.ingredient || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="纸管" :show-right-icon="false">
                        <view>{{ item.paperTubeList ? item.paperTubeList.map(x => x.name).join(',') : '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="成分" :show-right-icon="false">
                        <view>{{ item.ingredient || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="净重" :show-right-icon="false">
                        <view>{{ item.suttle || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="内袋" :show-right-icon="false">
                        <view>{{ item.innerBagList ? item.innerBagList.map(x => x.name).join() : '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="外袋" :show-right-icon="false">
                        <view>{{ item.outerBagList ? item.outerBagList.map(x => x.name).join() : '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="扎线" :show-right-icon="false">
                        <view>{{ item.bundleList ? item.bundleList.map(x => x.name).join() : '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="入库仓库" @click="onSelectWarehouse(index)" :show-right-icon="ruleForm.auditState !== 1" :show-star="ruleForm.auditState !== 1" :value="item.warehouseName" @clear="onClearWarehouseBtn(index)">
                        <view>{{ item.warehouseName || '' }}</view>
                    </jk-form-item>
                    <jk-form-item label="入库数量" :show-border-bottom="false" :show-star="ruleForm.auditState !== 1" :show-right-icon="ruleForm.auditState !== 1" :value="item.outInNumber" @clear="onClearNumBtn(index)" right-icon="edit-pen">
                        <u-input v-if="ruleForm.auditState !== 1" v-model="item.outInNumber" @blur="onTransferNumber($event, index, 'outInNumber')" :customStyle="{paddingLeft: 0}" :holdKeyboard="false" :adjustPosition="true" :cursorSpacing="30" type="digit" fontSize="28rpx" inputAlign="left" placeholder="入库数量" border="surround"></u-input>
                        <text v-else>{{ item.outInNumber }}</text>
                    </jk-form-item>
                </jkFormCard>
            </view>
            <view class="margin-top-30" v-if="ruleForm.auditState !== 1">
                <u-button @click="onSelectProduct" size="normal" icon="plus">添加</u-button>
            </view>
        </view>
		<view class="fixed-footer">
            <view v-if="ruleForm.auditState === 1" class="width-100-percentage">
                <view style="width: 100%;padding-right: 10rpx;"><u-button style="width: 100%;" @click="onToggleStateBtn" :loading="toggleBtnLoading" size="large" type="warning">{{ ruleForm.auditState ? '撤销审核' : '审核' }}</u-button></view>
            </view>
            <view v-else class="flex-start-center width-100-percentage">
                <view style="width: 100%;padding-right: 10rpx;"><u-button style="width: 100%;" @click="onConfirmBtn(0)" :disabled="showLoading" :loading="confirmLoading" size="large" type="primary">保存</u-button></view>
                <view style="width: 100%;padding-left: 10rpx;"><u-button style="width: 100%;" @click="onConfirmBtn(1)" :disabled="showLoading" :loading="confirmAndAuditLoading" size="large" type="success">保存并入库</u-button></view>
            </view>
		</view>
		<u-datetime-picker
            v-model="selectDateTime"
            :show="selectDateTimePickerState"
            mode="datetime"
			:closeOnClickOverlay="true"
            @confirm="onConfirmBtnOfSelectPicker"
            @close="onCloseBtnOfSelectPicker"
			@cancel="onCloseBtnOfSelectPicker"
        ></u-datetime-picker>
        <jkPopupOption
            :showAll="false"
            :value="ruleForm.warehouseId"
            :show="selectWarehousePopupOptionState"
            :optionList="warehouseList"
            @visible-change="(e) => selectWarehousePopupOptionState = e"
            @confirm="onConfirmOfSelectWarehouse"
        ></jkPopupOption>
	</view>
</template>

<script>
import {
    productionPrdNoticeGet,
    productionStockRecordCreate,
    productionStockRecordGet,
    productionStockRecordUpdate,
    productionStockRecordUpdateAuditState,
    yongYouInventoryProductStockTotal,
    yongYouWarehouseList
} from "../../../../api";
    import {
        formatTime,
        showLoading, tipBar
    } from "../../../../utils/jk-utils";
        import jkPopup from '../../../../jk-components/jk-popup';
    import jkFormCard from "../../../../jk-components/jk-from-card";
    import jkFormItem from "../../../../jk-components/jk-from-item";
    import jkPopupOption from "../../../../jk-components/jk-popup-option";
	export default {
        components: {
            jkPopupOption,
            jkFormCard,
            jkFormItem,
			jkPopup
		},
		data() {
			return {
                selectWarehousePopupOptionState: false,
                warehouseList: [],
				selectDateTime: '',
				selectDateTimePickerState: false,
				confirmLoading: false,
                confirmAndAuditLoading: false,
				activeTab: 0,
				dataId: null,
                showLoading: false,
				ruleForm: {
                    id: null,
                    belongDateTime: '',
                    empId: null,
                    empName: null,
                    warehouseId: null,
                    warehouseCode: '',
                    warehouseName: '',
                    workshopId: null,
                    workshopCode: '',
                    workshopName: '',
                    stockRecordItemList: [],
                    auditState: 0
				},
                editIdx: null,
                toggleBtnLoading: false,
			}
		},
		onLoad(e) {
            this.dataId = e.id;
            this.getDependentData();
        },
		onShow() {
		},
		methods: {
            onClearNumBtn(index) {
                this.$set(this.ruleForm.stockRecordItemList[index], 'outInNumber', 0);
            },
            onClearWarehouseBtn(index) {
                this.$set(this.ruleForm.stockRecordItemList[index], 'warehouseId', null);
                this.$set(this.ruleForm.stockRecordItemList[index], 'warehouseCode', '');
                this.$set(this.ruleForm.stockRecordItemList[index], 'warehouseName', '');
            },
            onToggleStateBtn() {
                this.toggleBtnLoading = true;
                productionStockRecordUpdateAuditState({id: this.ruleForm.id}).then(res => {
                    this.toggleBtnLoading = false;
                    if (res.data.status === 200) {
                        this.getDependentData();
                    }
                });
            },
            onSelectWarehouse(index) {
                if (this.ruleForm.auditState !== 1) {
                    this.editIdx = index;
                    this.selectWarehousePopupOptionState = true;
                }
            },
            onSelectProduct() {
                uni.navigateTo({
                    url: `/pages/production/packagePrd/outWarehouse/searchNotice?ids=${this.ruleForm.stockRecordItemList ? this.ruleForm.stockRecordItemList.map(x => x.packingPlanId).join(',') : ''}`
                });
            },
            onClearWarehouse() {
                this.$set(this.ruleForm, 'warehouseId', '');
                this.$set(this.ruleForm, 'warehouseCode', '');
                this.$set(this.ruleForm, 'warehouseName', '');
            },
            onConfirmOfSelectWarehouse(e, item) {
                if (this.editIdx || this.editIdx === 0) {
                    this.$set(this.ruleForm.stockRecordItemList[this.editIdx], 'warehouseId', item.id);
                    this.$set(this.ruleForm.stockRecordItemList[this.editIdx], 'warehouseCode', item.code);
                    this.$set(this.ruleForm.stockRecordItemList[this.editIdx], 'warehouseName', item.name);
                } else {
                    this.$set(this.ruleForm, 'warehouseId', item.id);
                    this.$set(this.ruleForm, 'warehouseCode', item.code);
                    this.$set(this.ruleForm, 'warehouseName', item.name);
                    this.ruleForm.stockRecordItemList.forEach(x => {
                        this.$set(x, 'warehouseId', item.id);
                        this.$set(x, 'warehouseCode', item.code);
                        this.$set(x, 'warehouseName', item.name);
                    });
                }

                this.selectWarehousePopupOptionState = false;
            },
            onSelectTime(type) {
                if (this.ruleForm.auditState !== 1) {
                    this.timeType = type;
                    this.selectDateTimePickerState = true;
                }
            },
            onScanBtn() {
                if (this.ruleForm.auditState === 1) return;
                let _this = this;
                // 允许从相机和相册扫码
                uni.scanCode({
                    success: function (res) {
                        let scanData = '';
                        try {
                            scanData = res.result;
                        } catch {
                            wx.showToast({
                                title: '无效的二维码',
                                icon: 'error'
                            })
                        }
                        if (scanData) {
                            wx.showModal({
                                title: '扫码结果',
                                content: `通知单号:${scanData}`,
                                success(res) {
                                    if (res.confirm) {
                                        _this.getDataDetailRequest(scanData);
                                    }
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '二维码格式不符',
                                icon: 'error'
                            })
                        }
                    }
                });
            },
            getDataDetailRequest(code) {
                return productionPrdNoticeGet({ code: code }).then(res => {
                    if (res.data.status === 200) {
                        let resData = res.data.res || null;
                        if (resData) {
                            this.ruleForm.stockRecordItemList.push(this.getPackagePlanItemInfo(resData));
                        }
                    }
                });
            },
            getPackagePlanItemInfo(x) {
                const ingredient = x.productOrderBatchItem && x.productOrderBatchItem.coarseSandList ? x.productOrderBatchItem.coarseSandList.filter(x => x.typeName === '粗纱').map(x => x.productName).join(' ; ') : '';
                return {
                    packingPlanId: x.id,
                    packingPlanCode: x.code,
                    productId: x.productId,
                    productCode: x.productCode,
                    productName: x.productName,
                    productModels: x.productModels,
                    batchId: x.batchId,
                    batchCode: x.batchCode,
                    bundleList: x.productOrderBatchItem && x.productOrderBatchItem.bundleList ? x.productOrderBatchItem.bundleList : [],
                    paperTubeList: x.productOrderBatchItem && x.productOrderBatchItem.paperTubeList ? x.productOrderBatchItem.paperTubeList : [],
                    outerBagList: x.productOrderBatchItem && x.productOrderBatchItem.outerBagList ? x.productOrderBatchItem.outerBagList : [],
                    innerBagList: x.productOrderBatchItem && x.productOrderBatchItem.innerBagList ? x.productOrderBatchItem.innerBagList : [],
                    ingredient: ingredient,
                    productionDateTime: `${formatTime(Date.now())}`,
                    suttle: x.productOrderBatchItem ? x.productOrderBatchItem.suttle : 0,
                    warehouseId: this.ruleForm.warehouseId,
                    warehouseCode: this.ruleForm.warehouseCode,
                    warehouseName: this.ruleForm.warehouseName,
                    productionQty: x.productionQty,
                    invalidDateTime: ''
                };
            },
            getDetailRequest() {
                return productionStockRecordGet({ id: this.dataId }).then(res => {
                    this.showLoading = false;
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res || {};
                    }
                });
            },
            onTransferNumber(e, index, keyName) {
                this.$set(this.ruleForm.stockRecordItemList[index], keyName, Number(e));
            },
            onOutputRatioBlur(e) {
                if (e > 1) {
                    this.$set(this.ruleForm, 'outputRatio', 1);
                }
            },
			onCloseBtnOfSelectPicker() {
				this.selectDateTimePickerState = false;
			},
			onConfirmBtnOfSelectPicker(e) {
				this.$set(this.ruleForm, this.timeType, formatTime(e.value));
				this.selectDateTimePickerState = false;
			},
			onConfirmBtn(e) {
                let params = JSON.parse(JSON.stringify(this.ruleForm));
                params.auditState = e;
                let api = !this.dataId ? productionStockRecordCreate : productionStockRecordUpdate;
                if (params.warehouseId && params.belongDateTime && params.stockRecordItemList && params.stockRecordItemList.length) {
                    if (e === 1) {
                        this.confirmAndAuditLoading = true;
                    } else {
                        this.confirmLoading = true;
                    }
                    if (!this.dataId) delete params.id;
                    api(params).then(res => {
                        this.confirmLoading = false;
                        this.confirmAndAuditLoading = false;
                        if (res.data.status === 200) {
                            uni.navigateBack({
                                delta: 1
                            });
                            tipBar('save');
                        }
                    })
                } else {
                    tipBar('validator');
                }
			},
			onTabChange(e) {
				this.activeTab = e;
			},
            getWarehouseListRequest() {
                return yongYouWarehouseList().then(res => {
                    if (res.data.status === 200) {
                        this.warehouseList = res.data.res;
                    }
                });
            },
            getProductItemStockRequest() {
                if (this.ruleForm.productId && this.ruleForm.warehouseCode && this.ruleForm.batchCode) {
                    return yongYouInventoryProductStockTotal({
                        productId:  this.ruleForm.productId,
                        warehouseCode:  this.ruleForm.warehouseCode,
                        batchCode:  this.ruleForm.batchCode
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.$set(this.ruleForm, 'beforeNumber', res.data.res.availableQuantity);
                        }
                    });
                }
            },
			async getDependentData() {
				showLoading(true);
				this.showLoading = true;
				if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDateTime', formatTime(Date.now()));
                }
                this.selectDateTime = formatTime(Date.now());
				await this.getWarehouseListRequest();
				if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
                showLoading(false);
			}
		}
	}
</script>

<style>

</style>
<style lang="scss" scoped>
	.machine-title {
		height: 42px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2d8cf0;
		border-radius: 12rpx;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
        border: solid 1px #2d8cf0;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		margin: 10rpx;
	}
	.popup-content-box {
		padding: 32rpx;
		.popup-content-box-title {
			font-size: 34rpx;
			text-align: center;
			margin-bottom: 20rpx;
		}
	}
</style>
